package com.witframework.dynoengine;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.witframework.cache.WitCache;
import com.witframework.cache.WitCacheFactory;
import com.witframework.dynoengine.model.WitMetaColumn;
import com.witframework.dynoengine.model.WitMetaColumnExt;
import com.witframework.dynoengine.model.WitMetaTable;
import com.witframework.util.StringTools;

public class MetaFactory {
	private static MetaFactory instance;
	private WitCache metaTableCache;
	private WitCache metaTableFieldCache;
	private WitCache metaTableFieldExtCache;
	private MetaFactory(){
		metaTableCache=WitCacheFactory.getCache(WitMetaTable.class);
		metaTableFieldCache=WitCacheFactory.getCache(WitMetaColumn.class);
		metaTableFieldExtCache=WitCacheFactory.getCache(WitMetaColumnExt.class);	
	}	
	public static MetaFactory getInstance(){
		if(instance==null){
			instance=new MetaFactory();			
		}
		return instance;
	}
	/**
	 * 刷新metatable数据缓存
	 */
	public void refresh(){		
		metaTableCache.removeAll();
		metaTableFieldCache.removeAll();
		metaTableFieldExtCache.removeAll();		
	}
	
	public WitMetaTable getMetaTableById(String id){		
		List rl=metaTableCache.find("id", id);
		return rl.size()>=1?(WitMetaTable)rl.get(0):null;		
	}
	
	public String[] getTablePK(String tableName){
		List pkList=new ArrayList();
		List<WitMetaColumn> mls=getMetaFileds(tableName);
		for(WitMetaColumn c:mls){
			if(StringTools.parseBoolean(c.getIsPkey()))
				pkList.add(c.getColumnName());				
		}
		return (String[]) pkList.toArray(new String[0]);		
	}
	/**
	 * 获取指定表的元数据
	 * @param name 表名称
	 * @return 表的元数据对象
	 */
	public WitMetaTable getMetaTableByName(String tableName){		
		List rl=metaTableCache.find("tableName", tableName);
		return rl.size()>=1?(WitMetaTable)rl.get(0):null;
	}
	/**
	 * 获取表列的元数据
	 * @param tableId
	 * @return
	 */
	public List getMetaFileds(String tableName){
		return metaTableFieldCache.find("tableName", tableName);
	}
	/**
	 * 获取指定表列的元数据
	 * @param tableName 表名称
	 * @param fieldName 列名称
	 * @return 列的元数据对象
	 */
	public WitMetaColumn getMetaFiled(String tableName,String fieldName){
		Map filter=new HashMap();
		filter.put("tableName", tableName);
		filter.put("columnName", fieldName);
		List rl= metaTableFieldCache.find(filter);
		return rl.size()>=1?(WitMetaColumn)rl.get(0):null;
	}
	
	
}
